#pragma once

#include <mutex>
#include <thread>
#include <atomic>
#include <memory>
#include <nlohmann/json.hpp>
#include "base_log.h"
#include "base_noncopyable.h"
#include "muxer_mp4_writer.h"
#include "media_stream.h"
#include "base_block_queue.h"
#include "base_time.h"

namespace El {
namespace Record {

class Recorder {
    DISALLOW_COPY_AND_MOVE(Recorder);

public:
    Recorder(int32_t ch);
    ~Recorder();

    bool SetConfig(uint32_t maxFileDuration, uint64_t maxFileSize, std::string storePath, bool overwrite);

    bool Start();

    void Stop();

    bool StartManual();

    void StopManual();

    bool GetRecordStatus() const;

private:
    void RecordThread();
    void CreateNewFile();
    void CloseCurrentFile();
    std::string GenerateFilename() const;
    bool CaptureAndSaveThumbnail(const std::string &videoFilename);
    void UpdateFileIndex(const std::string &filename);
    bool CheckEvents();
    void StartStream();
    void StopStream();
    void OnEvent(const nlohmann::json &alarm);
    bool CheckTimeJump();

private:
    int32_t ch_;
    std::unique_ptr<Muxer::MP4Writer> writer_;
    int32_t handle_{-1};
    std::mutex mutex_;
    bool isManualRecording_{false};

    // Thread management
    std::unique_ptr<std::thread> recordThread_;
    std::atomic<bool> running_{false};

    // 当前录像文件的索引信息
    nlohmann::json currentFileIndex_;

    // Recording parameters
    uint32_t maxFileDuration_{30 * 60};        // Default 30 minutes
    uint64_t maxFileSize_{2ULL * 1024 * 1024}; // Default 2GB, unit: kb
    std::string storePath_{"/mnt/udisk"};
    bool overwrite_{true};                      // Default true, enable overwrite when disk is full

    Media::StreamSourcePtr stream_{nullptr};
    
    int32_t eventHandle_{0};

    std::chrono::time_point<std::chrono::steady_clock> lastTime_{};
    struct AlarmInfo {
        nlohmann::json alarm;
        std::chrono::time_point<std::chrono::steady_clock> updateTime; // 事件更新时间(最新相同事件的时间)
        std::chrono::time_point<std::chrono::steady_clock> createTime; // 事件创建时间
        int32_t handle;
    };
    std::mutex alarmMutex_;
    std::queue<AlarmInfo> newList_;
    std::map<std::string, AlarmInfo> curMap_;
    
    // 时间检测相关
    std::chrono::system_clock::time_point lastCheckTime_{}; // 上次检查时间
    time_t lastDay_{0}; // 上一天的时间戳(0点)
};

using RecorderPtr = std::shared_ptr<Recorder>;

} // namespace Record
} // namespace El